package com.maxmlr.framework.mybatisplus.session;

import com.maxmlr.framework.mybatisplus.config.Configuration;
import com.maxmlr.framework.mybatisplus.executor.Executor;
import com.maxmlr.framework.mybatisplus.mapper.MapperData;
import com.maxmlr.framework.mybatisplus.mapper.MapperProxy;
import lombok.AllArgsConstructor;
import lombok.Data;

import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @ClassName DefaultSqlSession
 * @Description TODO
 * @Author maxiao
 * @Date 2020/3/23 上午11:21
 * @Version V1.0
 */
@Data
@AllArgsConstructor
public class DefaultSqlSession implements SqlSession {

    private Configuration configuration;
    private Executor executor;


    @Override
    public <T> List<T> selectList(MapperData<T> mapperData, Object parameter) throws Exception {
        return executor.query(mapperData, parameter);
    }

    @Override
    public <T> T selectOne(MapperData<T> mapperData, Object parameter) throws Exception {
        List<T> ts = selectList(mapperData, parameter);
        if (ts.isEmpty()) {
            return null;
        }
        return ts.get(0);
    }

    public <T> T getMapper(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz},
                new MapperProxy(this, clazz));
    }

}
